package mashibing.class8;

/**
 * 基数排序
 */
public class Class8_4_RadixSort {

    public static void radixSort(int[] arr){
        if(arr == null || arr.length < 2){
            return;
        }
        process(arr,getMaxBit(arr));
    }

    private static void process(int[] arr, int bit) {
        // 辅助数组
        for (int i = 0; i < bit; i++) {
            radix(arr,i);
        }
    }
    public static void radix(int[] arr,int bit){
        int[] count = new int[10];
        int[] help = new int[arr.length];
        for (int i = 0; i < arr.length; i++) {
            int num = getNumByBit(arr[i], bit);
            count[num]++;
        }
        for (int i = 1; i < count.length; i++) {
            count[i] = count[i - 1] + count[i];
        }
        for (int i = arr.length - 1; i >= 0; i--) {
            int num = getNumByBit(arr[i], bit);
            int index = count[num] - 1;
            count[num]--;
            help[index] = arr[i];
        }
        for (int i = 0; i < help.length; i++) {
            arr[i] = help[i];
        }
    }

    /**
     * 获取最大值位数
     */
    public static int getMaxBit(int[] arr){
        int max = Integer.MIN_VALUE;
        for (int i = 0; i < arr.length; i++) {
            max = Math.max(max,arr[i]);
        }
        int ans = 0;
        while (max != 0){
            max /= 10;
            ans++;
        }
        return ans;
    }

    public static int getNumByBit(int num,int bit){
        for (int i = 0; i < bit; i++) {
            if(num == 0){
                return 0;
            }
            num /= 10;
        }
        return num % 10;
    }
}
